﻿Imports System.IO

Public Class OfficerAttach
    Inherits System.Web.UI.Page

    Private dt As DataTable
    Private Property DataSource As Data.DataTable
        Get
            Return dt
        End Get
        Set(ByVal value As Data.DataTable)
            dt = value
        End Set
    End Property

    Private dtDetail As DataTable
    Private Property DataSourceDetail As Data.DataTable
        Get
            Return Me.Session("dtDetail")
        End Get
        Set(ByVal value As Data.DataTable)
            Me.Session("dtDetail") = value
        End Set
    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Me.Session.Remove("dtDetail")

            If Request.QueryString("infoid") <> "" Then
                Dim dt As DataTable = New DataTable
                Dim offinfo As Entity.OfficerInfoItem = New Entity.OfficerInfoItem
                offinfo.officer_id = Request.QueryString("infoid")
                txtOfficerID.Text = Request.QueryString("infoid")
                dt = BL.Officer.GetOfficerInfo(Request.QueryString("infoid"))
                If dt.Rows.Count > 0 Then
                    If Not IsDBNull(dt.Rows(0)("OFFICER_APP_ID")) Then txtOfficerAppID.Text = dt.Rows(0)("OFFICER_APP_ID")
                    If Not IsDBNull(dt.Rows(0)("OFFCIER_APP_TEL")) Then txtOfficerTel.Text = dt.Rows(0)("OFFCIER_APP_TEL")
                    If Not IsDBNull(dt.Rows(0)("OFFICER_FIRSTNAME_THA")) Then txtOfficerNameTH.Text = dt.Rows(0)("OFFICER_FIRSTNAME_THA")
                    If Not IsDBNull(dt.Rows(0)("OFFICER_LASTNAME_THA")) Then txtOfficerLastNameTH.Text = dt.Rows(0)("OFFICER_LASTNAME_THA")

                    GetHist(Request.QueryString("infoid"))
                End If
            End If

        End If
    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
        Try
            '***START: Attach File =============================================================================================================
            Dim SaveFlag As Boolean = True
            If txtDocumentName.Text.Trim = "" Then
                Me.Master.Alert("ชื่อเอกสาร ห้ามเป็นค่าว่าง\nกรุงณาระบุ ชื่อเอกสาร!")
                Exit Sub
            End If
            If Not (fupAttach.HasFile) Then
                Me.Master.Alert("คุณไม่ได้ทำการ Attach File\nกรุณาทำการ Attach File ที่ต้องการ!")
                Exit Sub
            End If

            Dim intLimitFileSizeinMB As Double = ConfigurationManager.AppSettings("LimitUploadFileSizeMB")
            Dim strFileType As String = ConfigurationManager.AppSettings("LimitUploadFileExtension")
            Dim lblFileSize As Double = intLimitFileSizeinMB
            Dim arrFileExtension As String() = strFileType.Split("|")

            Dim intFileSize As Integer = fupAttach.PostedFile.ContentLength
            Dim fileExt As String
            fileExt = System.IO.Path.GetExtension(fupAttach.FileName)
            fileExt = fileExt.ToUpper

            If (intFileSize / 1024 / 1024) > lblFileSize Then
                'Limit File Size
                Me.Master.Alert("ขนาดของไฟล์ห้ามเกิน " & lblFileSize & " MB.\nกรุณาแนบเอกสารใหม่")
                Exit Sub
            End If

            If Array.IndexOf(arrFileExtension, fileExt) = -1 Then
                Me.Master.Alert("ไม่สามารถแนบเอกสารได้ เนื่องจากระบบอนุญาติให้แนบเอกสารสกุล " & strFileType.Replace("|", ", ") & " เท่านั้น")
                Exit Sub
            End If

            Dim DirInfo As New DirectoryInfo(Server.MapPath("Attachment"))
            If Not DirInfo.Exists Then
                DirInfo.Create()
            End If

            Dim OffDirInfo As New DirectoryInfo(Server.MapPath("Attachment\" & GlobalApp.Authen.offcier_id))
            If Not OffDirInfo.Exists Then
                OffDirInfo.Create()
            End If

            Dim oFullPath As String = ""
            oFullPath = Server.MapPath("Attachment\" & GlobalApp.Authen.offcier_id) & "\" & fupAttach.FileName
            Dim ofile As New IO.FileInfo(oFullPath)
            Dim ofileExists As Boolean = ofile.Exists
            If (Not chbUpload.Checked) AndAlso ofileExists Then
                Me.Master.Alert("ไม่สามารถแนบเอกสารได้! เนื่องจากเอกสารที่แนบมีอยู่แล้วในระบบ")
                Exit Sub
            End If

            fupAttach.SaveAs(oFullPath)

            '***END: Attach File =============================================================================================================


            'Insert or Update Attach Info to Database=========================================================================================

            Dim oSaveFlag As Boolean = True
            Dim info As Entity.OfficerAttach = New Entity.OfficerAttach
            info.attach_file_path = oFullPath
            info.officer_id = Convert.ToDecimal(txtOfficerID.Text.Trim)
            info.attach_file_name = txtDocumentName.Text.Trim
            info.attach_file_remark = txtDescription.Text.Trim
            info.record_status = "Y"
            info.upd_user_id = GlobalApp.Authen.offcier_id
            info.upd_date = Common.UtilityDateTime.ConvertDate(Now.ToString("dd/MM/yyyy", Common.Utility.CulInfo)).Value

            If (Not ofileExists) Then
                info.create_user_id = GlobalApp.Authen.offcier_id
                info.create_date = Common.UtilityDateTime.ConvertDate(Now.ToString("dd/MM/yyyy", Common.Utility.CulInfo)).Value
                oSaveFlag = BL.Officer.InsertOfficerAttach(info)
            Else
                oSaveFlag = BL.Officer.UpdateOfficerAttachByPath(info)
            End If

            If oSaveFlag Then
                GetHist(txtOfficerID.Text.Trim)
                ClearPayment()
                Me.Master.Alert("SUCCESS.\nทำการ แนบเอกสาร สำเร็จ")
            Else
                Me.Master.Alert("FAIL!\nทำการ แนบเอกสาร ไม่สำเร็จ")
            End If

        Catch ex As Exception
            Common.LogError.AddLogException(ex)
            Me.Master.Alert("ไม่สามารถแนบเอกสารที่ท่านต้องการได้")
        End Try
    End Sub

    Protected Sub btnReset_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnReset.Click
        Me.Session.Remove("dtDetail")
        Me.Response.Redirect("~/OfficerManagement.aspx", False)
    End Sub

    Private Sub Bind(ByVal pageIndex As Integer)
        Me.gvList.DataSource = DataSourceDetail
        Me.gvList.PageIndex = pageIndex
        Me.gvList.DataBind()
    End Sub

    Private Sub gvList_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvList.RowCommand
        Try
            If e.CommandName = "Showfile" Then
                Me.ClientScript.RegisterClientScriptBlock(Me.GetType, "Attachment", "window.open('OfficerAttachOpen.aspx?attachid=" & e.CommandArgument & "', 'attachment','');", True)
            ElseIf e.CommandName = "DeleteFile" Then
                Dim info As Entity.OfficerAttach = New Entity.OfficerAttach
                info.attach_id = Convert.ToDecimal(e.CommandArgument)
                info.record_status = "N"
                info.upd_user_id = GlobalApp.Authen.offcier_id
                info.upd_date = Common.UtilityDateTime.ConvertDate(Now.ToString("dd/MM/yyyy", Common.Utility.CulInfo)).Value

                Dim attDt As DataTable = New DataTable
                attDt = BL.Officer.GetOfficerAttachById(Convert.ToDecimal(e.CommandArgument))
                If BL.Officer.UpdateOfficerAttach(info) Then
                    Try
                        Dim TheFile As New FileInfo(attDt.Rows(0).Item("ATTACH_FILE_PATH"))
                        If TheFile.Exists Then
                            File.Delete(attDt.Rows(0).Item("ATTACH_FILE_PATH"))
                        End If
                    Catch ex As Exception
                        info.record_status = "Y"
                        info.upd_date = Common.UtilityDateTime.ConvertDate(Now.ToString("dd/MM/yyyy", Common.Utility.CulInfo)).Value
                        BL.Officer.UpdateOfficerAttach(info)
                    End Try
                    GetHist(txtOfficerID.Text.Trim)
                    Me.Master.Alert("SUCCESS.\nทำการลบ เอกสาร สำเร็จ")
                Else
                    Me.Master.Alert("FAIL!\nทำการลบ เอกสาร ไม่สำเร็จ")
                End If
            End If
        Catch ex As Exception
            Me.Master.Alert("ไม่สามารถดึงข้อมูลที่ท่านต้องการได้")
            Common.LogError.AddLogException(ex)
        End Try
    End Sub

    Private Sub GetHist(ByVal OfficeID As String)
        DataSourceDetail = BL.Officer.GetOfficerAttach(OfficeID)
        Bind(0)
        'If DataSourceDetail.Rows.Count > 0 Then
        '    Bind(0)
        'End If
    End Sub

    Private Sub ClearPayment()
        txtDocumentName.Text = ""
        txtDescription.Text = ""
    End Sub

End Class